﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TwilioSharp.Code.Twilio;
using TwilioSharp.Code.Twilio.Types;

namespace TwilioSharp.Code.Filters
{
    public class TwilioFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            var twilioApi = new TwilioApi();
            if (!string.IsNullOrEmpty(request["AccountGuid"]) && request["AccountGuid"] == twilioApi.AccountGuid  )
            {
                filterContext.HttpContext.Items["CallRequest"] = ParseCallReqeust(request);
                filterContext.HttpContext.Items["CallRequestGeoData"] = ParseCallRequestGeoData(request);
            }
            base.OnActionExecuting(filterContext);
        }

        private static CallRequest ParseCallReqeust(HttpRequestBase request)
        {
            var callRequest = new CallRequest()
            {
                CallGuid = request["CallGuid"] ?? "",
                Caller = request["Caller"] ?? "",
                Called = request["Called"] ?? "",
                AccountGuid = request["AccountGuid"] ?? ""
            };

            switch (request["CallStatus"] ?? "")
            {
                case "in-progress":
                    callRequest.CallStatus = CallRequest.CallStatusTypes.InProgress;
                    break;
                case "completed":
                    callRequest.CallStatus = CallRequest.CallStatusTypes.Completed;
                    break;
                case "busy":
                    callRequest.CallStatus = CallRequest.CallStatusTypes.Busy;
                    break;
                case "failed":
                    callRequest.CallStatus = CallRequest.CallStatusTypes.Failed;
                    break;
                case "no-answer":
                    callRequest.CallStatus = CallRequest.CallStatusTypes.NoAnswer;
                    break;
            }

            return callRequest;
        }

        private static CallRequestGeoData ParseCallRequestGeoData(HttpRequestBase request)
        {
            var callRequestGeoData = new CallRequestGeoData()
            {
                CallerCity = request["CallerCity"] ?? "",
                CallerState = request["CallerState"] ?? "",
                CallerZip = request["CallerZip"] ?? "",
                CallerCountry = request["CallerCountry"] ?? "",
                CalledCity = request["CalledCity"] ?? "",
                CalledState = request["CalledState"] ?? "",
                CalledZip = request["CalledZip"] ?? "",
                CalledCountry = request["CalledCountry"] ?? ""
            };
            return callRequestGeoData;
        }
    }
}